﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models;
using IOA.MES.Client.Models.Response;
using IOA.MES.Client.Settings;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using System.Reflection;
using IOA.MES.Client.Top.TopTcp;

namespace IOA.MES.Client.Top
{
    /// <summary>
    /// TopIndex.xaml 的交互逻辑
    /// </summary>
    public partial class TopIndex : Window
    {
        private FileSystemWatcher watcher;
        private string lastBarCode = string.Empty;
        private List<ViaSiteRecord> records { get; set; } = new List<ViaSiteRecord>();
        private List<Machine> machines { get; set; } = new List<Machine>();
        private List<MachineAddressSetting> machineSettings = new List<MachineAddressSetting>();
        private TopServer appServer;
        public TopIndex()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtTrueName.Content = BaseEnv.UserInfo.TrueName;
            InitDuties();
            InitRecords();
            InitMachines();

            var plcAddressJson = BaseEnv.GetStorage("TopPLCAddresses");
            machineSettings = string.IsNullOrWhiteSpace(plcAddressJson) ? new List<MachineAddressSetting>() : JsonConvert.DeserializeObject<List<MachineAddressSetting>>(plcAddressJson);

            appServer = new TopServer(MessageReceived);
            if (!appServer.Setup(2001))
            {
                MessageBox.Show("TCP服务启动失败");
                return;
            }
            if (!appServer.Start())
            {
                MessageBox.Show("TCP端口打开失败");
                return;
            }
        }

        #region 初始化数据
        public void InitDuties()
        {
            var duties = BaseEnv.InvokeApi<QueryDutiesResponse>("/api/Auth/QueryDuties", new { WorkshopCode = BaseEnv.WorkshopCode }).Data.Duties;

            cbDuties.ItemsSource = duties;
            cbDuties.DisplayMemberPath = "DutyName";
            cbDuties.SelectedValuePath = "DutyId";

            if (duties.Any())
            {
                cbDuties.SelectedIndex = 0;
            }
        }

        private void cb_DutyChanged(object sender, SelectionChangedEventArgs e)
        {
            InitRecords();
        }

        public void InitMachines()
        {
            machines = BaseEnv.InvokeApi<QueryMachinesResponse>("/api/Machine/QueryMachines", new { WorkshopCode = BaseEnv.WorkshopCode, MachineType = MachineType.TopMachine }).Data.Machines;
        }

        private void InitRecords()
        {
            new TaskFactory().StartNew(() =>
            {
                Thread.Sleep(100);
                Dispatcher.Invoke(new Action(() =>
                {
                    var response = BaseEnv.InvokeApi<QueryViaSiteRecordsResponse>("/api/Machine/QueryViaSiteRecords", new { DutyId = Convert.ToInt32(cbDuties.SelectedValue), SiteType = SiteType.Top });
                    if (response.ErrCode != 200)
                    {
                        CommonMessage.Alert(this, response.ErrMsg);
                        return;
                    }
                    records.Clear();
                    records.AddRange(response.Data.Records);
                    records.ForEach(_ => _.No = records.Count - records.IndexOf(_));
                    BindGridRecords();
                }));
            });
        }

        private void BindGridRecords()
        {
            gridRecords.ItemsSource = null;
            gridRecords.ItemsSource = records;
            lbTotal.Content = records.Select(_ => _.Code.ToUpper().Trim()).Distinct().Count();
        }
        #endregion

        /// <summary>
        /// 接收设备报文
        /// </summary>
        public void MessageReceived(string ip, string message)
        {
            message = message.Trim(';');
            if (string.Equals(message, "NG"))
            {
                return;
            }
            var machine = machineSettings.FirstOrDefault(_ => string.Equals(_.Address, ip, StringComparison.CurrentCultureIgnoreCase));
            if (machine == null)
            {
                CommonMessage.Alert(this, $"IP地址无法识别：{ip}");
                return;
            }

            ViaSite(machine.MachineId, message, machine.Floor);
        }

        /// <summary>
        /// 过站请求
        /// </summary>
        public void ViaSite(int machineId, string code, string position)
        {
            Dispatcher.Invoke(new Action(() =>
            {
                txtBarCode.Text = code;
                var request = new
                {
                    SiteType = SiteType.Top,
                    DutyId = Convert.ToInt32(cbDuties.SelectedValue),
                    MachineId = machineId,
                    Code = code,
                    TopPosition = position
                };
                var response = BaseEnv.InvokeApi<ViaSiteResponse>("/api/Machine/ViaSite", request);
                if (response.ErrCode != 200)
                {
                    CommonMessage.Alert(this, response.ErrMsg, false);
                    return;
                }
                CommonMessage.Log(LogLevel.Info, $"过站成功：{code}");
                txtWorkOrderNo.Text = response.Data.ViaSiteRecord.WorkOrderNo;

                if (response.Data.DutyId != Convert.ToInt32(cbDuties.SelectedValue))
                {
                    cbDuties.SelectedValue = response.Data.DutyId;
                }
                else if (!records.Any(_ => string.Equals(_.Code, response.Data.ViaSiteRecord.Code, StringComparison.CurrentCultureIgnoreCase)))
                {
                    response.Data.ViaSiteRecord.No = records.Count + 1;
                    records.Insert(0, response.Data.ViaSiteRecord);
                    BindGridRecords();
                }
            }));
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (watcher != null)
            {
                watcher.EnableRaisingEvents = false;
                watcher.Dispose();
            }
        }

        private void Menu_Click(object sender, RoutedEventArgs e)
        {
            switch (((MenuItem)sender).Name)
            {
                case "btnSettings":
                    new SettingsIndex().ShowDialog();
                    break;
                case "btnPLCSettings":
                    new TopSetting().ShowDialog();
                    break;
                case "btnMissingRecords":
                    new MissingSiteRecord(0).Show();
                    break;
                case "btnLogout":
                    new LoginWindow(false).Show();
                    this.Hide();
                    break;
                case "btnAbout":
                    MessageBox.Show($"AISUNMes Product Version:{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion}");
                    break;
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (appServer != null)
            {
                appServer.Stop();
            }
            Environment.Exit(0);
        }
    }
}
